package com.copa.l692;

import java.util.*;

/**
 * @author copa
 * @createDate 2022-06-14 11:53
 * @function 哈希表+堆（堆排列跟Test1反过来）
 */
public class Test2 {

    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        for (String word : words) {
            if (hashMap.containsKey(word)) {
                hashMap.put(word, hashMap.get(word) + 1);
                continue;
            }
            hashMap.put(word, 1);
        }
        PriorityQueue<String> queue = new PriorityQueue<>(
                ((o1, o2) -> hashMap.get(o1).equals(hashMap.get(o2)) ? o1.compareTo(o2) : hashMap.get(o2) - hashMap.get(o1))
        );
        List<String> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            queue.add(entry.getKey());
        }
        for (int i = 0; i < k; i++) {
            result.add(queue.poll());
        }
        return result;
    }

    public static void main(String[] args) {
        String[] words = {"i", "love", "leetcode", "i", "love", "coding"};
        List<String> result = new Test2().topKFrequent(words, 2);
        for (String s : result) {
            System.out.println(s);
        }
    }
}
